package com.tianruan.psychological.common.utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: Dong
 * @Email: dong980514280@gmail.com
 * @Create: 2019-11-19 15:39
 * @PS HTTP网络工具类
 */
public class HttpUtils {

    public static String get(String url) throws IOException, URISyntaxException {
        return get(url, null, null);
    }

    public static String get(String url, Map<String, String> paramsMap) throws IOException, URISyntaxException {
        return get(url, paramsMap, null);
    }

    public static String get(String url, Map<String, String> paramsMap, Map<String, String> headersMap) throws IOException, URISyntaxException {
        String returnValue = "";
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            HttpPost httpPost = new HttpPost(url);

            StringBuilder tempUrl = new StringBuilder(url);

            if (paramsMap != null) {
                tempUrl.append('?');
                for (Map.Entry<String, String> param: paramsMap.entrySet()) {
                    tempUrl.append(param.getKey() + "=" + param.getValue() + "&");
                }
            }

            //创建URIBuilder
            URIBuilder uri = new URIBuilder(tempUrl.toString());

            //创建httpGet对象
            HttpGet httpGet = new HttpGet(uri.build());

            //设置请求的报文头部的编码
            httpGet.setHeader(
                    new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

            //设置期望服务端返回的编码
            httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

            if (headersMap != null) {
                for (Map.Entry<String, String> param: headersMap.entrySet()) {
                    httpGet.setHeader(new BasicHeader(param.getKey(), param.getValue()));
                }
            }
            // 发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时，必须用此方法

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 处理返回值
        return returnValue;
    }

    public static CloseableHttpResponse post(String url) throws URISyntaxException, IOException {
        return post(url, null, null);
    }

    public static CloseableHttpResponse post(String url, Map<String, String> paramsMap) throws URISyntaxException, IOException {
        return post(url, paramsMap, null);
    }

    public static CloseableHttpResponse post(String url, Map<String, String> paramsMap, Map<String, String> headersMap) throws URISyntaxException, IOException {
        //创建一个httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建URIBuilder
        URIBuilder uri = new URIBuilder(url);

        HttpPost httpPost = new HttpPost(uri.build());
        if (paramsMap != null) {
            // 设置参数
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                paramList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(paramList, StringUtils.CHARSET_NAME));
        }

        //设置请求的报文头部的编码
        httpPost.setHeader(
                new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
        //设置期望服务端返回的编码
        httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

        if (headersMap != null) {
            for (Map.Entry<String, String> param: headersMap.entrySet()) {
                httpPost.setHeader(new BasicHeader(param.getKey(), param.getValue()));
            }
        }

        return client.execute(httpPost);
    }

    public static String postJson(String url, String json) {
        return postJson(url, json, null);
    }

    public static String postJson(String url, String json, Map<String, String> headersMap) {
        String returnValue = "";
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            HttpPost httpPost = new HttpPost(url);

            // 给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);

            if (headersMap != null) {
                for (Map.Entry<String, String> param: headersMap.entrySet()) {
                    httpPost.setHeader(new BasicHeader(param.getKey(), param.getValue()));
                }
            }
            // 发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时，必须用此方法

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 处理返回值
        return returnValue;
    }

//    public static CloseableHttpResponse put(String url, Map<String, String> paramsMap, Map<String, String> headersMap) throws URISyntaxException, IOException {
//        //创建一个httpclient对象
//        CloseableHttpClient client = HttpClients.createDefault();
//        //创建URIBuilder
//        URIBuilder uri = new URIBuilder(url);
//
//        HttpPut httpPut = new HttpPut(uri.build());
//
//        return client.execute(httpPost);
//    }

}
